package com.lagou.http;

import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.handler.codec.http.*;
import io.netty.util.CharsetUtil;

/**
 * http服务端业务处理类
 */
public class NettyHttpServerHandler extends SimpleChannelInboundHandler<HttpObject> {


    /**
     * 读取就绪事件
     *
     * @param ctx
     * @param msg
     * @throws Exception
     */
    @Override
    protected void channelRead0(ChannelHandlerContext ctx, HttpObject msg) throws Exception {
        //1.判断是不是http请求
        if (msg instanceof HttpRequest) {
            DefaultHttpRequest defaultHttpRequest = (DefaultHttpRequest) msg;
            if ("/favicon.ico".equals(defaultHttpRequest.uri())) {
                System.out.println("图标不响应!");
                return;
            }
            System.out.println("浏览器请求路径: " + defaultHttpRequest.uri());
            //2.给浏览器响应
            ByteBuf byteBuf = Unpooled.copiedBuffer("Hello! 我是Netty服务器", CharsetUtil.UTF_8);
            DefaultFullHttpResponse httpResponse = new DefaultFullHttpResponse(HttpVersion.HTTP_1_1,
                    HttpResponseStatus.OK,
                    byteBuf);
            //3.设置响应头
            httpResponse.headers().add(HttpHeaderNames.CONTENT_TYPE, "text/html;charset=utf-8");
            httpResponse.headers().add(HttpHeaderNames.CONTENT_LENGTH, byteBuf.readableBytes());
            ctx.writeAndFlush(httpResponse);
        }
    }
}
